<template>
  <div class="app-container">
    <el-form label-position="right" label-width="auto">
      <el-form-item label="公司全称" required>
        <el-input v-model="form.shopName"></el-input>
      </el-form-item>
      <el-form-item label="公司地址" required>
        <ShopAddr ref="shopAddr" :addr.sync="form.shopAddr" />
      </el-form-item>
      <el-form-item label="详细地址" required>
        <el-input v-model="form.detailAddr"></el-input>
      </el-form-item>
      <el-form-item label="经纬度">
        <div class="latitude-box">
          <el-input v-model="form.latitudeC"></el-input>
          <el-button @click.prevent="getLatitudeC()">获取经纬度</el-button>
        </div>
      </el-form-item>
      <el-form-item label="公司电话">
        <el-input v-model="form.shopPhone"></el-input>
      </el-form-item>
      <el-form-item label="公司传真">
        <el-input v-model="form.shopFax"></el-input>
      </el-form-item>
      <el-form-item label="公司网址">
        <el-input v-model="form.shopWeb"></el-input>
      </el-form-item>
      <el-form-item label="公司邮箱">
        <el-input v-model="form.shopEmail"></el-input>
      </el-form-item>
      <el-form-item label="联系人信息">
        <el-button type="success" @click="addContact()"
          >点击增加一个联系人</el-button
        >
        <div
          class="contact-person"
          v-for="(item, index) of count"
          :key="item.uuid"
          style="display:flex"
        >
          <el-form-item label-width="100px" :label="'联系人' + (index + 1)">
            <el-input v-model="item.username"></el-input>
          </el-form-item>
          <el-form-item label-width="100px" label="联系电话">
            <el-input v-model="item.phone"></el-input>
          </el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="count.splice(index, 1)"
          ></el-button>
        </div>
      </el-form-item>
      <el-form-item label="营业执照号">
        <el-input v-model="form.businessCode"></el-input>
      </el-form-item>
      <el-form-item label="经营范围">
        <el-input
          type="textarea"
          :autosize="{ minRows: 4 }"
          v-model="form.businessScope"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业安全生产许可证">
        <Upload
          typeName="proCertificate"
          :fileList="proCertificate"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
        />
      </el-form-item>
      <el-form-item label="营业执照">
        <Upload
          typeName="businessLicense"
          :fileList="businessLicense"
          :validatorFn="validatorFn"
          @removeFile="needRemoveFile"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认提交</el-button>
      </el-form-item>
    </el-form>
    <Progress v-if="showProgress" :percentageNum="percentageNum" />
  </div>
</template>

<script>
import Upload from "@/components/upload";
import { getUploadKey, ossUpload, getFileList, delFile } from "@/api/upload";
import ShopAddr from "@/components/addr";
import { getShopOne, updateShopOne } from "@/api";
export default {
  name: "ContactInfo",
  components: {
    Upload,
    ShopAddr
  },
  data() {
    return {
      form: {
        shopName: "",
        shopAddr: "110000,110100,110101,110101001",
        detailAddr: "",
        latitudeC: "",
        shopPhone: "",
        shopFax: "",
        shopWeb: "",
        shopEmail: "",
        businessCode: "",
        businessScope: ""
      }, // 初始化信息
      initData: {},
      // 联系人信息
      count: [],
      // 生产许可证
      proCertificate: [],
      //营业执照
      businessLicense: [],
      //上传文件数--------------------------------------------
      uploadFileNum: 0,
      //文件上传数--------------------------------------------
      uploadSuccessNum: 0,
      // 需要删除的文件uuid
      delFileUuid: "",
      // 当前上传文件列表
      currentUploadList: [],
      //是否显示进度
      showProgress: false
    };
  },

  created() {
    this.getLoginShop();
  },
  computed: {
    percentageNum() {
      let currentUpload = 0;
      let total = 0;
      this.currentUploadList.forEach(item => {
        currentUpload += item.loaded;
        total += item.total;
      });
      return ((currentUpload / total) * 100) | 0;
    }
  },
  methods: {
    // 获取商家主体信息
    async getLoginShop() {
      let res = await getShopOne({
        uuid: this.$store.getters.shopUuid
      }).catch(err => console.log(err));
      if (res.state == 100) {
        this.count = [...res.items.count];
        for (const key in this.form) {
          if (this.form.hasOwnProperty.call(this.form, key)) {
            this.$set(this.form, key, res.items.list[key]);
          }
        }
        this.initData = { ...res.items };
      }

      this.getAllFile();
    },

    // 获取全部文件
    getAllFile() {
      //查询文件--------------------------------------------
      const params = {
        page: 0,
        pageSize: 0,
        parentUuid: this.$store.getters.shopUuid
      };
      getFileList(params).then(res => {
        if (res.state == 100) {
          this.proCertificate = [];
          this.businessLicense = [];
          res.items.forEach(item => {
            if (item.typeName == "proCertificate") {
              this.proCertificate.push(item);
            } else if (item.typeName == "businessLicense") {
              this.businessLicense.push(item);
            }
          });
        }
      });
    },

    //校验文件
    validatorFn(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      return isJPG && isLt2M;
    },

    // 确定修改
    onSubmit() {
      // 修改
      this.updateShopOne();
      // 删除文件
      this.removeFile();
    },

    //更新或增加商店主体信息
    updateShopOne() {
      const data = {
        count: [...this.count],
        list: { ...this.form, uuid: this.$store.getters.shopUuid }
      };
      updateShopOne(data).then(res => {
        if (res.state == 100) {
          if (this.needUploadList().length == 0) {
            this.$message({
              type: "success",
              message: res.msg
            });
          } else {
            this.addFile();
          }
        }
      });
    },

    // 获取经纬度
    getLatitudeC() {
      let nodeList = this.$refs.shopAddr.getCheckedNodes();
      const lat = nodeList[0].data.lat;
      const lng = nodeList[0].data.lng;
      this.form.latitudeC = lat + "," + lng;
    },

    // 添加联系人
    addContact() {
      this.count.push({
        uuid: new Date().getTime(),
        username: "",
        phone: "",
        shopUuid: this.$store.getters.shopUuid
      });
    },

    // 是否有需要上传的文件
    needUploadList() {
      return this.proCertificate
        .concat(this.businessLicense)
        .filter(item => item.raw);
    },

    // 需要删除的文件
    needRemoveFile(file) {
      let uuid = file[0].uuid || null;
      if (uuid) {
        this.delFileUuid += uuid + ",";
      }
    },

    // 删除文件操作
    removeFile() {
      if (this.delFileUuid) {
        const params = {
          uuid: this.delFileUuid
        };
        delFile(params).then(res => {
          if (res.state == 100 && this.needUploadList().length == 0) {
            this.$message({ type: "success", message: "修改成功" });
          }
        });
      }
    },

    // 上传文件
    addFile() {
      this.uploadSuccessNum = 0;
      this.uploadFileNum = 0;
      const shopData = {
        uuid: this.$store.getters.shopUuid,
        shopUuid: this.$store.getters.shopUuid
      };
      this.showProgress = true;
      this.currentUploadList = [];
      this.needUploadList().forEach((fileItem, index) => {
        this.currentUploadList.push({
          loaded: 0,
          total: 0
        });
        this.uploadFileNum += 1;
        this.getUploadKey(shopData, fileItem, index);
      });
    },

    //获取上传凭证--------------------------------------------
    async getUploadKey(shopData, fileItem, index) {
      const data = {
        fileName: fileItem.name,
        fileSize: fileItem.size,
        parentUuid: shopData.uuid,
        shopUuid: shopData.shopUuid,
        typeName: fileItem.typeName
      };
      const res = await getUploadKey(data);
      if (res.state == 100) {
        this.ossUpload(res.items, fileItem, index);
      }
    },

    //上传阿里云--------------------------------------------
    async ossUpload(key, fileItem, index) {
      const formData = new FormData();
      formData.append("policy", key.policy);
      formData.append("OSSAccessKeyId", key.accessid);
      formData.append("success_action_status", 200);
      formData.append("signature", key.signature);
      formData.append("key", key.dir);
      formData.append("file", fileItem.raw);
      const host = key.host;
      const res = await ossUpload(formData, host, this.uploadCallback, index);
      if (res.status === 200) {
        this.uploadSuccessNum += 1;
        if (this.uploadSuccessNum == this.uploadFileNum) {
          this.uploadSuccessNum = 0;
          this.uploadFileNum = 0;
          this.showProgress = false;
          this.$message({ type: "success", message: "修改成功" });
        }
      }
    },

    //上传回调--------------------------------------------
    uploadCallback(progress, index) {
      let uploadData = {
        loaded: progress.loaded,
        total: progress.total
      };
      this.currentUploadList.splice(index, 1, uploadData);
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  max-width: 1080px;
  // 经纬度
  .latitude-box {
    display: flex;
    align-items: center;

    .el-button {
      color: #0090ff;
      margin-left: 5px;
    }
  }

  .contact-person {
    margin: 10px 0;

    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
